/**
 * Created by lyt on 2018.11.
 * 一些公共方法
 */
// 变量申明
let app = require('common'),
    api = require('api'),
    dialog = require('dialog'),
    Tracer = require('tracer'),
    hosturl = (location.origin || (location.protocol + '//' + location.hostname));
require("SM4")
let off = true;

new Tracer({
    token: window.location.host.indexOf('yunzhi.co') > -1 ? 'boAtfivSxytlcwNB' : 'tsyCHuJkelpnhxCC', //boAtfivSxytlcwNB
    reportUrl: window.location.host.indexOf('yunzhi.co') > -1 ? "https://arms.yunliketech.com/arms/r.png" : "https://arms.8ylk.cn/arms/r.png"
})

let cat = {
    // 自定义上报msg 监控
    reportMsg(eventName, eventDetail) {
        // let $jlUserinfo = app.getValue('jlUserinfo','local'),
        //     $wxLogin = app.getValue('wxLogin','local'),
        //     jlUserinfo = $jlUserinfo&&JSON.parse($jlUserinfo),
        //     wxLogin = $wxLogin&&JSON.parse($wxLogin);
        // try{
        //     let userinfo = {
        //         phone:wxLogin.phone,
        //         nickName:jlUserinfo.nickname
        //     }
        //     __bb.setUserInfo(JSON.stringify(userinfo));
        // }catch(e){}

        __bb.msg(`${eventName}::${eventDetail}`);
    },
    /***是否微信打开**/
    isWeChat: (callback) => {
        // debugger
        let ua = navigator.userAgent.toLowerCase();
        if (ua.match(/MicroMessenger/i) == "micromessenger") {
            //每次去授权获取最新usertoken
            // var userToken = app.getValue('token', 'local') || '';
            var wxcode = app.getValue('wxcode', 'session') || '';
            if (!wxcode) {
                // 微信授权
                cat.wxWarrantyBase();
            } else {
                return callback && callback();
            }
        } else {
            alert('请在微信中打开！')
        }

    },
    /*** 微信授权 **/
    wxWarranty: () => {
        // 存储返回路径
        let wappId = window.th.wappId,
            wredirectUri = `${window.th.Domain}?${hosturl}${window.th.callPage}`;
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wappId}&redirect_uri=${wredirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE&forcePopup=true&forceSnapShot=true#wechat_redirect`;
        // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wappId}&redirect_uri=${wredirectUri}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect`;
        return false;
    },
    /*** 微信授权 **/
    wxWarrantyBase: () => {
        let eurl = window.location.href;
        app.storeValue('url', eurl, 'session');

        // 存储返回路径
        let wappId = window.th.wappIdBase,
            wredirectUri = `${window.th.Domain}?${hosturl}${window.th.callPage}`;
        // window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wappId}&redirect_uri=${wredirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE&forcePopup=true&forceSnapShot=true#wechat_redirect`;
        window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${wappId}&redirect_uri=${wredirectUri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`;
        return false;
    },

    /*** 左上角返回按钮**/
    backOut: () => {
        window.history.back();
        return false;
    },
    /**
     * 跳积分商城
     */
    gotoPointmall: () => {
        let userToken = app.getValue('userToken', 'session');
        window.location.href = hosturl + "/pointmall/index.html?userToken=" + userToken;
    },
    codecalculagraph: (sum, callback) => {
        if (off) {
            off = false;
            let job = $('.ui-codesyle'),
                remclass = 'ui-codegray';
            let codeTime = setInterval(() => {
                sum--;
                job.html(`还剩${sum}秒`);
                if (sum == 0) {
                    clearInterval(codeTime);
                    job.html(`重新获取`);
                    off = true;
                    job.removeClass(remclass);
                }
            }, 1000);
            job.addClass(remclass);
            return callback && callback();
        }
    },
    loginTimeout: (msg, job) => {
        msg && dialog.tipDialog(msg);
        logintimes = setTimeout(() => {
            clearTimeout(logintimes);
            // app.linkTo('login', job);
        }, 2600);
    },
    // 解密sm4
    sm4Decry(data) {
        
        var sm4Config = {
            // encrypt/decypt main key; cannot be omitted
            // key: 'JeF8U9wHFOMfs2Y8',
            key: 'JeF38U9wT9wlMfs2',
            // optional; can be 'cbc' or 'ecb'
            mode: 'ecb', // default
            // optional; when use cbc mode, it's necessary
            iv: 'UISwD9fW6cFh9SNS', // default is null
            // optional: this is the cipher data's type; Can be 'base64' or 'text'
            cipherType: 'base64' // default is base64

        }

        var sm4 = new smCrypt(sm4Config);

        if (data != null && data != '' && data != undefined) {
            var obj = sm4.decrypt(data);
            return JSON.parse(obj);
        } else {
            return '';
        }

    },
    base64toFile(dataurl, filename) {

        var arr, mime, bstr, n, u8arr, suffix;
        try {
            arr = dataurl.split(',');
            mime = arr[0].match(/:(.*?);/)[1];
            suffix = mime.split('/')[1];
            bstr = atob(arr[1]);
            n = bstr.length;
            u8arr = new Uint8Array(n);
        } catch (error) {
            mime = "image/png";
            suffix = 'png';
            bstr = atob(dataurl);
            n = bstr.length;
            u8arr = new Uint8Array(n);
        }

        while (n--) {
            u8arr[n] = bstr.charCodeAt(n)
        }
        return new File([u8arr], `${filename}.${suffix}`, {

            type: mime

        })

    },
    // checkBackUrl
    // 当返回的URL 中有 ?
    checkBackUrl(str) {
        let regStr = new RegExp(/\?/, "i")

        if (regStr.test(str)) {
            // 包含?
            return str + "&data="
        }

        return str + "?data="

    },
    validatePhoneNumber(phoneNumber) {
        var reg = /^1[3|4|5|6|7|8|9][0-9]{9}$/;
        return reg.test(phoneNumber);
    },
    /**
     * 防止重复执行
     * @param {*} func 
     * @param {*} delay 
     * @returns 
     */
    preventRepeatedClicks(func, delay) {
        let timer;
        return function() {
            return new Promise((resolve, reject) => {
                if (!timer) {
                    timer = setTimeout(() => {
                        timer = null;
                        func.apply(this, arguments);
                        resolve();
                    }, delay);
                } else {
                    reject('Click in progress');
                }
            });
        }
    },
    

};
module.exports = cat;